package com.ncbee.base.config.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.ncbee.base.config.shiro.util.ShiroFilterUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author fengzirong
 * @DESC 主要解决
 * 1    ajax 请求时 用户没有登录  则跳转到登录界面
 * 2    判断用户是否登录，如果登录就跳转到指定的登录界面
 * @Date 2019/1/2 20:38
 **/
public class CustomUserAccessFilter extends AccessControlFilter {
    private static final Logger logger = LoggerFactory.getLogger(CustomUserAccessFilter.class);
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject=SecurityUtils.getSubject();
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        if(subject.isAuthenticated()){//用户已认证
            boolean isLoginPage=isLoginRequest(servletRequest,servletResponse);
            if(isLoginPage){//如果已经认证过了，直接跳转到系统首页
                logger.info("--------用户已经登录默认跳转到系统首页-----------");
                response.sendRedirect("common/index");
            }
        }
        boolean isAjax=ShiroFilterUtils.isAjax(request);
        //
        if(isAjax){
            if(!subject.isAuthenticated()){//当用户没有登录时，跳转到登录界面
                String url=request.getRequestURI();
                boolean isLoginPage=url.contains(this.getLoginUrl());
                if(isLoginPage){//如果是登录界面
                    logger.info("--------用户登录状态已失效两秒之后调到登录界面-----------");
                    JSONObject result=new JSONObject();
                    result.put("msg","登录状态已失效两秒之后调到登录界面");
                    result.put("code","login_again");
                    response.getWriter().write(result.toJSONString());
                    return false;//本过滤器已经处理
                }
            }
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return false;
    }
}
